#include <unistd.h>
#include <pthread.h>
#include <errno.h>

pthread_cond_t wait_th[] = { PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER };
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;;

int current = 0;
const char data[] = {'A', 'B', 'C', 'D'};

void* th(void *arg) {
	int id = (int)arg;
	char c;

	while(1) {
		pthread_mutex_lock(&mtx);
		while(current != id) {
			// wait 上一个线程
			pthread_cond_wait(&wait_th[(id + 3) % 4], &mtx);
		}

		// 下一个线程可以被唤醒了
		current = (id + 1) % 4;;
		write(STDOUT_FILENO, &data[id], 1);
		pthread_mutex_unlock(&mtx);

		// 唤醒下一个线程
		pthread_cond_signal(&wait_th[id]);
		usleep(10);
	}
}



int main() {
	int ret, i;

	pthread_t tid[4];

	for (i = 0; i < 4; ++i) {
		ret = pthread_create(&tid[i], NULL, th, (void*)i);
		if (ret != 0) {
			errno = ret;
			perror("create th");
			return 1;
		}	
	}
		
	pthread_cond_signal(&wait_th[3]);

	for (i = 0; i < 4; ++i) {
		pthread_join(tid[i], NULL);
	}
}
